<template>
	<view class="photo-album-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-content">
				<view class="back-btn" @click="goBack">
					<text class="back-icon">‹</text>
				</view>
				<text class="navbar-title">我的相册</text>
				<view class="placeholder"></view>
			</view>
		</view>

		<!-- 分类标签区域 -->
		<view class="category-tabs">
			<view 
				class="tab-item"
				:class="{ active: activeCategory === category.key }"
				v-for="category in categories"
				:key="category.key"
				@click="switchCategory(category.key)"
			>
				<text class="tab-text">{{ category.name }}</text>
			</view>
		</view>

		<!-- 筛选按钮区域 -->
		<view class="filter-section">
			<view 
				class="filter-btn"
				:class="{ active: activeFilter === filter.key }"
				v-for="filter in filters"
				:key="filter.key"
				@click="switchFilter(filter.key)"
			>
				<text class="filter-text">{{ filter.name }}</text>
			</view>
			<view class="sort-btn" @click="showSortOptions">
				<text class="sort-text">筛选</text>
				<text class="sort-arrow">▼</text>
			</view>
		</view>

		<!-- 免费解锁提示 -->
		<view class="unlock-tip">
			<view class="unlock-icon">🔓</view>
			<text class="unlock-text">可免费解锁4套写真</text>
		</view>

		<!-- 相册分组展示 -->
		<view class="album-groups">
			<template v-if="displayGroups.length > 0">
			<view 
				class="album-group"
				v-for="group in displayGroups"
				:key="group.id"
			>
				<!-- 分组标题和查看全部 -->
				<view class="group-header">
					<view class="group-info">
						<text class="group-title">{{ group.title }}</text>
						<view class="group-meta">
							<text class="group-author">{{ group.author }}</text>
								<text class="group-points">{{ group.points }}积分</text>
						</view>
					</view>
					<view class="view-all-btn" @click="viewAllPhotos(group)">
							<text class="view-all-text">查看全部({{ group.photos ? group.photos.length : 0 }})</text>
						<text class="view-all-arrow">›</text>
					</view>
				</view>

					<!-- 照片网格 - 只显示第一张照片 -->
				<view class="photo-grid">
					<view 
						class="photo-item"
							@click="previewPhoto(group.photos && group.photos.length > 0 ? group.photos[0] : null, group)"
							v-if="group.photos && group.photos.length > 0"
					>
						<!-- 视频项显示封面图和播放图标 -->
							<template v-if="group.photos[0].isVideo">
							<image 
									:src="group.photos[0].coverImage || group.photos[0].thumbnail"
								mode="aspectFill" 
								class="photo-image"
							></image>
							<view class="video-indicator">
								<text class="video-icon">▶</text>
									<text class="video-duration">{{group.photos[0].duration || '0:15'}}</text>
							</view>
						</template>
						
						<!-- 普通图片项 -->
						<template v-else>
							<image 
									:src="group.photos[0].thumbnail" 
								mode="aspectFill" 
								class="photo-image"
							></image>
						</template>
						
						<!-- 待解锁状态覆盖层 -->
							<view class="photo-overlay" v-if="group.photos[0].status === 'locked'">
							<view class="lock-status">
								<text class="lock-text">待解锁</text>
							</view>
						</view>
					</view>
						<view class="empty-grid" v-if="!group.photos || group.photos.length === 0">
							<text>暂无照片</text>
				</view>
					</view>
				</view>
			</template>
			
			<!-- 空状态提示 -->
			<view class="empty-state" v-else>
				<image src="https://cdn.zhzfpn.cn/PicGo/20250903191401596.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">暂无相册内容</text>
				<text class="empty-subtext">快去制作你的AI写真吧</text>
			</view>
		</view>

		<!-- 底部安全区域 -->
		<view class="bottom-safe-area"></view>
	</view>
</template>

<script>
import { consumeCreditsForPhoto } from '@/api/ai-trip/credit.js'

export default {
	data() {
		return {
			activeCategory: 'portrait',
			activeFilter: 'all',
			categories: [
				{ key: 'portrait', name: 'AI写真' },
				{ key: 'travel', name: 'AI视频' }
			],
			filters: [
				{ key: 'all', name: '全部' },
				{ key: 'unlocked', name: '已解锁' }
			],
			// 初始化空的相册分组数据
			albumGroups: {
				portrait: [],
				travel: []
			}
		}
	},
	computed: {
		displayGroups() {
			// 确保albumGroups和activeCategory存在
			if (!this.albumGroups || !this.activeCategory || !this.albumGroups[this.activeCategory]) {
				return [];
			}
			
			const groups = this.albumGroups[this.activeCategory];
			
			// 确保groups是数组
			if (!Array.isArray(groups)) {
				return [];
			}
			
			if (this.activeFilter === 'unlocked') {
				return groups
					.filter(group => group && typeof group === 'object')
					.map(group => {
						// 确保photos属性存在且是数组
						const photos = Array.isArray(group.photos) ? group.photos : [];
						
						return {
					...group,
							photos: photos.filter(photo => photo && photo.status === 'unlocked')
						};
					})
					.filter(group => group.photos && group.photos.length > 0);
			}
			
			return groups;
		}
	},
	
	onLoad(options) {
		// 加载用户生成的作品
		this.loadUserWorks();
		
		// 处理传入的参数
		if (options) {
			// 如果指定了分类，切换到对应分类
			if (options.category && this.categories.some(c => c.key === options.category)) {
				this.activeCategory = options.category;
				console.log('根据参数切换到分类:', this.activeCategory);
			}
			
			// 记录来源
			if (options.source) {
				console.log('页面来源:', options.source);
				// 可以根据不同来源做特定处理
				if (options.source === 'faceswap') {
					// 来自图片换脸页面
					this.activeFilter = 'all'; // 默认显示全部
				} else if (options.source === 'videofusion') {
					// 来自视频换脸页面
					this.activeCategory = 'aiVideo'; // 默认显示AI视频分类
				}
			}
		}
	},
	
	methods: {
		goBack() {
			uni.navigateBack();
		},
		
		switchCategory(categoryKey) {
			this.activeCategory = categoryKey;
			// 添加触觉反馈
			uni.vibrateShort({
				type: 'light'
			});
		},
		
		switchFilter(filterKey) {
			this.activeFilter = filterKey;
		},
		
		showSortOptions() {
			uni.showActionSheet({
				itemList: ['按时间排序', '按类型排序'],
				success: (res) => {
					console.log('选择排序方式:', res.tapIndex);
				}
			});
		},
		
		viewAllPhotos(group) {
			console.log('查看全部照片:', group);
			uni.showToast({
				title: `查看${group.title}全部照片`,
				icon: 'none'
			});
		},
		
		previewPhoto(photo, group) {
			if (!photo) return;
			
			if (photo.status === 'locked') {
				uni.showModal({
					title: '解锁照片',
					content: '该照片需要解锁后才能查看，是否立即解锁？',
					confirmText: '立即解锁',
					cancelText: '取消',
					success: (res) => {
						if (res.confirm) {
							this.unlockPhoto(photo);
						}
					}
				});
			} else {
				// 根据类型预览已解锁的内容
				if (photo.isVideo) {
					// 预览视频
					console.log('预览视频:', photo.fullImage);
					uni.navigateTo({
						url: `/pages/ai-trip/ai_video/player/index?videoUrl=${encodeURIComponent(photo.fullImage)}&title=${encodeURIComponent(group ? group.title : '视频预览')}`
					});
				} else {
					// 预览图片
					uni.previewImage({
						current: photo.fullImage,
						urls: [photo.fullImage]
					});
				}
			}
		},
		
		unlockPhoto(photo) {
			// 显示加载中提示
			uni.showLoading({
				title: '解锁中...'
			});
			
			// 调用API函数解锁图片
			consumeCreditsForPhoto({
				photo_id: photo.id,
				category_type: this.activeCategory
			})
				.then(res => {
					uni.hideLoading();
					
					if (res.code === 200) {
						// 解锁成功 - 更新本地存储
						this.updateLocalUnlockStatus(photo.id);
						
						uni.showToast({
							title: '解锁成功！',
							icon: 'success',
							success: () => {
								// 延迟一下再重新加载页面
								setTimeout(() => {
									uni.reLaunch({
										url: '/pages/ai-trip/my_photo/index'
									});
								}, 1500);
							}
						});
					}
				})
				.catch(error => {
					uni.hideLoading();
					
					// 处理错误情况
					if (error.code === 403) {
						// 积分不足
						const requiredCredits = error.data?.required_credits || 1;
						
						uni.showModal({
							title: '积分不足',
							content: `解锁该图片需要${requiredCredits}积分，您当前积分不足，是否前往充值？`,
							confirmText: '去充值',
							cancelText: '取消',
							success: (modalRes) => {
								if (modalRes.confirm) {
									// 跳转到充值页面
									uni.navigateTo({
										url: '/pages/user/recharge/index'
									});
								}
							}
						});
					} else if (error.code === 404) {
						// 图片不存在
						uni.showToast({
							title: '图片资源不存在',
							icon: 'none'
						});
					} else {
						// 其他错误
						uni.showToast({
							title: error.message || '解锁失败，请稍后重试',
							icon: 'none'
						});
					}
				});
		},
		
		// 更新本地存储中的解锁状态
		updateLocalUnlockStatus(photoId) {
			try {
				// 获取已解锁图片ID列表
				const unlockedPhotos = uni.getStorageSync('unlocked_photos') || [];
				console.log('更新前已解锁图片列表:', unlockedPhotos);
				
				// 如果该图片ID不在列表中，则添加
				if (!unlockedPhotos.includes(photoId)) {
					unlockedPhotos.push(photoId);
					uni.setStorageSync('unlocked_photos', unlockedPhotos);
					console.log('更新后已解锁图片列表:', unlockedPhotos);
				} else {
					console.log('图片ID已存在于解锁列表中:', photoId);
				}
			} catch (e) {
				console.error('更新本地解锁状态失败:', e);
			}
		},
		
		// 加载用户生成的所有作品（合并了之前的三个加载方法）
		loadUserWorks() {
			try {
				// 获取所有本地存储的键
				const keys = uni.getStorageInfoSync().keys;
				
				// 加载AI视频作品
				this.loadVideoWorks(keys);
				
				// 加载AI写真作品
				this.loadPhotoWorks(keys);
				
				// 加载人脸融合作品
				this.loadFaceSwapWorks(keys);
				
			} catch (error) {
				console.error('加载用户作品失败:', error);
			}
		},
		
		// 加载图片作品
		loadPhotoWorks(keys) {
			const photoWorkKeys = keys.filter(key => key.startsWith('generated_photo_works_'));
			
			if (photoWorkKeys.length === 0) {
				console.log('未找到图片作品缓存');
				return;
			}
			
			console.log('找到图片作品缓存键:', photoWorkKeys);
			
			// 获取已解锁的图片ID列表
			const unlockedPhotos = uni.getStorageSync('unlocked_photos') || [];
			
			const photoWorks = [];
			
			photoWorkKeys.forEach(key => {
				const works = uni.getStorageSync(key) || [];
				if (works.length > 0) {
					const templateInfo = works[0];
					
					photoWorks.push({
						id: parseInt(key.split('_').pop()) || 1000 + photoWorks.length,
						title: templateInfo.templateTitle || 'AI写真作品',
						date: new Date().toISOString().split('T')[0],
						author: '驴小拍',
						points:99,
						photos: works.map((work, index) => {
							const photoId = 10000 + index;
							const isUnlocked = unlockedPhotos.includes(photoId);
							
							return {
								id: photoId,
								thumbnail: work.photoUrl,
								fullImage: work.photoUrl,
								status: isUnlocked ? 'unlocked' : 'locked',
								isVideo: false
							};
						})
					});
				}
			});
			
			if (photoWorks.length > 0) {
				this.albumGroups.portrait = [...this.albumGroups.portrait, ...photoWorks];
				console.log('已加载图片作品:', photoWorks);
			}
		},

		// 加载视频作品
		loadVideoWorks(keys) {
			const videoWorkKeys = keys.filter(key => key.startsWith('generated_video_works_'));
			
			if (videoWorkKeys.length === 0) {
				console.log('未找到视频作品缓存');
				return;
			}
			
			console.log('找到视频作品缓存键:', videoWorkKeys);
			
			// 获取已解锁的图片ID列表
			const unlockedPhotos = uni.getStorageSync('unlocked_photos') || [];
			
			const videoWorks = [];
			
			videoWorkKeys.forEach(key => {
				const works = uni.getStorageSync(key) || [];
				if (works.length > 0) {
					const templateInfo = works[0];
					
					videoWorks.push({
						id: parseInt(key.split('_').pop()) || 1000 + videoWorks.length,
						title: templateInfo.templateTitle || 'AI视频作品',
						date: new Date().toISOString().split('T')[0],
						author: '驴小拍',
						points: 15,
						photos: works.map((work, index) => {
							const photoId = 10000 + index;
							const isUnlocked = unlockedPhotos.includes(photoId);
							
							return {
								id: photoId,
								thumbnail: work.videoUrl,
								fullImage: work.videoUrl,
								status: isUnlocked ? 'unlocked' : 'locked',
								isVideo: true,
								duration: work.duration || '0:15',
								coverImage: work.coverImage || work.templateImage
							};
						})
					});
				}
			});
			
			if (videoWorks.length > 0) {
				this.albumGroups.aiVideo = videoWorks;
				console.log('已加载视频作品:', videoWorks);
			}
		},
		
		// 加载人脸融合作品
		loadFaceSwapWorks(keys) {
			const faceSwapKeys = keys.filter(key => {
				return key.startsWith('generated_works_') || 
					   /generated_works_\d+_mt_/.test(key);
			});
			
			console.log('找到人脸融合作品缓存键:', faceSwapKeys);
				
			if (faceSwapKeys.length === 0) {
				console.log('未找到人脸融合作品缓存');
				return;
			}
			
			// 获取已解锁的图片ID列表
			const unlockedPhotos = uni.getStorageSync('unlocked_photos') || [];
			console.log('已解锁的图片ID列表:', unlockedPhotos);
			
			const faceSwapWorks = [];
			
			faceSwapKeys.forEach(key => {
				const works = uni.getStorageSync(key) || [];
				console.log(`键 ${key} 中的数据:`, JSON.stringify(works));
			
				if (works.length > 0) {
					const templateInfo = works[0];
					
					const workGroup = {
						id: parseInt(key.split('_')[2]) || 2000 + faceSwapWorks.length,
						title: templateInfo.templateTitle || 'AI换脸作品',
						date: new Date().toISOString().split('T')[0],
						author: '驴小拍',
						points: 10,
						photos: works.map((work, index) => {
							// 使用templateId作为photo_id，与前端photo.id保持一致
							const photoId = templateInfo.templateId;
							const isUnlocked = unlockedPhotos.includes(photoId);
							console.log(`图片ID ${photoId} 是否已解锁:`, isUnlocked);
							
							return {
								id: photoId, // 使用templateId作为ID，与前端保持一致
								thumbnail: work.resultImage,
								fullImage: work.resultImage,
								status: isUnlocked ? 'unlocked' : 'locked',
								isVideo: false,
								originalImage: work.originalResultImage || work.resultImage
							};
						})
					};
					
					console.log('创建的作品组:', JSON.stringify(workGroup));
					faceSwapWorks.push(workGroup);
				}
			});
			
			console.log('处理后的人脸融合作品:', JSON.stringify(faceSwapWorks));
			
			if (faceSwapWorks.length > 0) {
				this.albumGroups.portrait = [...this.albumGroups.portrait, ...faceSwapWorks];
				console.log('更新后的portrait数组:', JSON.stringify(this.albumGroups.portrait));
			}
		}
	}
}
</script>

<style scoped>
.photo-album-container {
	width: 100%;
	min-height: 100vh;
	background: linear-gradient(180deg, #f0f8ff 0%, #e6f3f7 50%, #fff5f0 100%);
	color: #333;
}

/* 自定义导航栏 */
.custom-navbar {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 1000;
	background: rgba(240, 248, 255, 0.9);
	padding-top: var(--status-bar-height, 44rpx);
}

.navbar-content {
	height: 88rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
}

.back-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
    font-size: 70rpx; /* 增大字体尺寸，原来可能是24rpx左右 */
    font-weight: bold; /* 加粗显示 */
    color: #333; 
}

.navbar-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
}

.placeholder {
	width: 60rpx;
}

/* 分类标签区域 */
.category-tabs {
	margin-top: calc(88rpx + var(--status-bar-height, 44rpx));
	padding: 30rpx 30rpx 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.tab-item {
	flex: 1;
	text-align: center;
	padding: 20rpx 0;
	position: relative;
}

.tab-item.active .tab-text {
	color: #5dade2;
	font-weight: 600;
}

.tab-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 60rpx;
	height: 4rpx;
	background: #5dade2;
	border-radius: 2rpx;
}

.tab-text {
	font-size: 32rpx;
	color: #666;
	transition: all 0.3s ease;
}

/* 筛选按钮区域 */
.filter-section {
	padding: 0 30rpx 30rpx;
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.filter-btn {
	background: rgba(255, 255, 255, 0.8);
	border: 1rpx solid rgba(93, 173, 226, 0.3);
	border-radius: 40rpx;
	padding: 16rpx 32rpx;
	transition: all 0.3s ease;
}

.filter-btn.active {
	background: rgba(93, 173, 226, 0.1);
	border-color: rgba(93, 173, 226, 0.8);
}

.filter-text {
	font-size: 28rpx;
	color: #666;
}

.filter-btn.active .filter-text {
	color: #5dade2;
}

.sort-btn {
	margin-left: auto;
	background: rgba(255, 255, 255, 0.8);
	border: 1rpx solid rgba(93, 173, 226, 0.3);
	border-radius: 40rpx;
	padding: 16rpx 24rpx;
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.sort-text {
	font-size: 28rpx;
	color: #666;
}

.sort-arrow {
	font-size: 20rpx;
	color: #999;
}

/* 免费解锁提示 */
.unlock-tip {
	margin: 0 30rpx 40rpx;
	background: linear-gradient(135deg, rgba(93, 173, 226, 0.1) 0%, rgba(88, 214, 141, 0.1) 100%);
	border: 1rpx solid rgba(93, 173, 226, 0.3);
	border-radius: 16rpx;
	padding: 20rpx 24rpx;
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.unlock-icon {
	font-size: 32rpx;
}

.unlock-text {
	font-size: 28rpx;
	color: #58d68d;
	font-weight: 500;
}

/* 相册分组展示 */
.album-groups {
	padding: 0 30rpx;
}

.album-group {
	margin-bottom: 60rpx;
}

.group-header {
	display: flex;
	justify-content: space-between;
	align-items: flex-end;
	margin-bottom: 24rpx;
	padding-bottom: 16rpx;
}

.group-info {
	flex: 1;
}

.group-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #ffffff;
	display: block;
	margin-bottom: 8rpx;
}

.group-meta {
	display: flex;
	align-items: center;
	gap: 16rpx;
}

.group-author {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.5);
}

.group-points {
	font-size: 24rpx;
	color: #ffffff;
	font-weight: 600;
}

.view-all-btn {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 8rpx 16rpx;
	background: rgba(51, 51, 51, 0.8);
	border-radius: 20rpx;
	border: 1rpx solid rgba(102, 102, 102, 0.5);
}

.view-all-text {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
}

.view-all-arrow {
	font-size: 28rpx;
	color: rgba(255, 255, 255, 0.8);
	font-weight: 300;
}

/* 照片网格 */
.photo-grid {
	display: flex;
	gap: 20rpx;
}

.photo-item {
	flex: 1;
	aspect-ratio: 3/4;
	border-radius: 16rpx;
	overflow: hidden;
	position: relative;
	background: rgba(51, 51, 51, 0.5);
	border: 1rpx solid rgba(102, 102, 102, 0.3);
}

.photo-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
}

/* 视频指示器 */
.video-indicator {
	position: absolute;
	bottom: 10rpx;
	right: 10rpx;
	background: rgba(0, 0, 0, 0.6);
	border-radius: 10rpx;
	padding: 4rpx 8rpx;
	display: flex;
	align-items: center;
	gap: 4rpx;
}

.video-icon {
	font-size: 24rpx;
	color: #ffffff;
}

.video-duration {
	font-size: 20rpx;
	color: #ffffff;
	font-weight: 500;
}

/* 待解锁状态覆盖层 */
.photo-overlay {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.7);
	display: flex;
	align-items: center;
	justify-content: center;
	backdrop-filter: blur(4rpx);
}

.lock-status {
	background: #00ff88;
	color: #000000;
	padding: 12rpx 24rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	font-weight: 600;
	box-shadow: 0 4rpx 12rpx rgba(0, 255, 136, 0.3);
}

.lock-text {
	font-size: 24rpx;
	color: #000000;
}

/* 空状态样式 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
	opacity: 0.6;
}

.empty-text {
	font-size: 32rpx;
	color: rgba(255, 255, 255, 0.8);
	margin-bottom: 10rpx;
}

.empty-subtext {
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.5);
}

.empty-grid {
	flex: 1;
	aspect-ratio: 3/4;
	border-radius: 16rpx;
	background: rgba(51, 51, 51, 0.3);
	display: flex;
	align-items: center;
	justify-content: center;
}

.empty-grid text {
	color: rgba(255, 255, 255, 0.5);
	font-size: 24rpx;
}

/* 底部安全区域 */
.bottom-safe-area {
	height: calc(40rpx + env(safe-area-inset-bottom));
}

/* 响应式设计 */
@media (max-width: 600rpx) {
	.category-tabs {
		padding: 30rpx 20rpx 20rpx;
	}
	
	.tab-text {
		font-size: 28rpx;
	}
	
	.filter-section {
		padding: 0 20rpx 30rpx;
		gap: 15rpx;
	}
	
	.album-groups {
		padding: 0 20rpx;
	}
	
	.photo-grid {
		gap: 15rpx;
	}
}

/* 动画效果 */
.photo-item {
	transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.photo-item:active {
	transform: scale(0.98);
	box-shadow: 0 8rpx 24rpx rgba(0, 255, 136, 0.3);
}

.filter-btn, .sort-btn, .view-all-btn {
	transition: all 0.3s ease;
}

.filter-btn:active, .sort-btn:active, .view-all-btn:active {
	transform: scale(0.98);
	opacity: 0.8;
}
</style>